#!/bin/bash
# commandtodnp prototype driver
# Copyright 2012 Atomic Pepper LLC
# $Rev: 587 $


############################################
###### DO NOT MODIFY PARAMETERS BELOW ######
############################################
SVN_ID='$Id: rastertodnp 676 2009-03-17 22:30:56Z tyler $'
svn_vers=${SVN_ID#$'\x24Id: rastertodnp '};svn_vers=${svn_vers%% *}
PATH=$PATH:/usr/bin:/bin:/usr/sbin:/sbin
############################################
####### START OF FUNCTION DEFINITIONS ######
############################################
function cleanupOnExit ()
{
  db "cleaning up."
  local -i code=${1:-$?}
#rm -rf "${tmp_dir}"
  if ((0 == g_got_SIGPIPE));then
   db "Task complete with exit code $code"
   ((code)) && fatal
  fi
  db "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"
}

function logDate ()
{
    date '+[%Y/%m/%d %H:%M:%S %z]'
}
function db ()
{
    ((g_got_SIGPIPE)) ||
	>&2 echo "DEBUG: commandtodnp: $@"
}
usage () {
  >&2 echo "usage: $0 job-id user title copies options [file]";
  exit 1
}
function info ()
{
    ((g_got_SIGPIPE)) ||
	>&2 echo "INFO: $@"
}
function ppdEmit ()
{
    ((g_got_SIGPIPE)) ||
	>&2 echo "PPD: $@"
}
function cups_Attribute ()
{
    ((g_got_SIGPIPE)) ||
	>&2 echo ATTR: $1="${2}"
}
function dumpViz ()
{
   local line IFS='
'
   local -a multi=($(echo -n "$@" | unvis | hexdump -Cv))
#   unset IFS
   for line in "${multi[@]}" ;do db $line;done
}
function dumpString ()
{
   local line IFS='
'
   local -a multi=($(echo -en "$@" | hexdump -Cv))
   for line in "${multi[@]}" ;do db $line;done
}
stripLeadingZeros ()
{
    local t;
    local v=$1;
    until test "$t" == "$v"; do
        t=$v;
        v=${v#0};
    done;
    echo $v
}



###################################################################################
# DNP USB status functions follow
###################################################################################
function dnp_GetPrinterStatus ()
{
# send the get status command and read a reply
cmd='\x1bPSTATUS                        '
db "Sending GetPrinterStatus command"
echo -en "${cmd}"
}

function dnp_GetMedia ()
{
# send the get media command and read a reply
cmd='\x1bPINFO  MEDIA                   '
db "Sending GetMedia command"
echo -en "${cmd}"
}

function dnp_GetFreeBuffers ()
{
# send the get free buffers command and read a reply
cmd='\x1bPINFO  FREE_PBUFFER            '
db "Sending GetFreeBuffers command"
echo -en "${cmd}"
}

function dnp_GetPrintsRemaining ()
{
# send the get prints remaining command and read a reply
cmd='\x1bPINFO  MQTY                    '
db "Sending GetPrintsRemaining command"
echo -en "${cmd}"
}

function  dnp_getUSBReply ()
{
  # pass any argument to this function to surpress the logging of reply
   local noDump=$1
   local i=0
   # read CUPS backchannel data on fd3
   # reply size is the first 8 bytes in UTF8 decimal digits
   local header
    header="$(2>/dev/null dd if=/dev/fd/3 bs=8 count=1|vis -w)";
   until test "$header";do
    ((3 == i)) && { db "failed to read reply";exit; }
    sleep $((++i))
    header="$(2>/dev/null dd if=/dev/fd/3 bs=8 count=1|vis -w)";
   done
   test "$noDump" || dumpViz "${header}"
   size=$(stripLeadingZeros "${header}" )
   if ((0 < size));then
     db "reading $size bytes from backchannel"
     response="$(2>/dev/null dd if=/dev/fd/3 bs=$((size)) count=1|vis -w)" &&
      test "$noDump" || dumpViz "$response"
   fi
}

############################################
####### END OF FUNCTION DEFINITIONS ########
############################################
# verify correct argc
(($# == 5 || $# == 6)) || usage

trap gotTERM TERM HUP QUIT
trap gotPIPE PIPE
trap cleanupOnExit EXIT 

# parse input stream for a supported command and execute

if((6 == $#)); then

# redirect file on argv[6] to stdin
  exec <$6
fi

while read command arg; do
 case ${command} in 

AutoConfigure)
#############
dnp_GetMedia
dnp_getUSBReply

#response is a string starting 0nnnn\r
mediaType=${response//\\^@}
mediaType=${mediaType//\\^M}
mediaType=${mediaType#MT}
ppdEmit PrinterInstalledMedia=$mediaType
;;


ReportStatus)
############
db "Getting printer status"
dnp_GetPrinterStatus
dnp_getUSBReply

#response is a string starting 0nnnn\r
state=${response//\\^@}
state=${state//\\^M}
ppdEmit PrinterStatus=$state
 ;; 
ReportLevels)
############
dnp_GetPrintsRemaining
dnp_getUSBReply

#response is a string starting MQTY0157\r
MQTY=${response//\\^@}
MQTY=${MQTY//\\^M}
qty=$(stripLeadingZeros ${MQTY#MQTY})

ppdEmit MediaRemaining=$qty
cups_Attribute "marker-message" "$qty prints remaining"
cups_Attribute "marker-colors" "#00FFFF#FF00FF#FFFF00"
cups_Attribute "marker-low-levels" "10"
cups_Attribute "marker-levels" "$((qty/2))"
cups_Attribute "marker-names" "ribbon"
;;

esac
done

###################################################################################


